package com.asset.dispoal.company.service.commom;

import com.asset.dispoal.company.domain.db.entity.SysCompanyDo;
import com.asset.dispoal.company.domain.db.mapper.SysCompanyMapper;
import com.asset.dispoal.company.dto.CompanyRequest;
import com.asset.dispoal.company.dto.CompanyResponse;
import com.asset.dispoal.company.service.converter.CompanyConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.core.protocol.page.PageUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;
import tech.mhuang.pacebox.springboot.protocol.data.Page;
import tech.mhuang.pacebox.springboot.protocol.data.PageVO;

import java.util.List;

/**
 * @author qr
 * @date 2022/1/25$
 */
@Component
public class CompanyPageCommand implements BaseCommand<CompanyRequest, Result<PageVO<CompanyResponse>>> {


    @Autowired
    SysCompanyMapper sysCompanyMapper;


    @Override
    public Result<PageVO<CompanyResponse>> execute(CompanyRequest request) {
        final SysCompanyDo companyDo = CompanyConverter.INSTANCE.reqToDo(request);
        companyDo.setPermission((String) GlobalHeaderThreadLocal.get().getExtraMap().get("permission"));
        PageVO<CompanyResponse> pageVO = new PageVO<>();
        pageVO.setTotalSize(sysCompanyMapper.pageCount(companyDo));
        if (PageUtil.checkPage(pageVO.getTotalSize(), companyDo)) {
            Page<SysCompanyDo> page = new Page<>();
            page.setRecord(companyDo);
            page.setStart((companyDo.getStart() - 1) * companyDo.getRows());
            page.setRows(companyDo.getRows());
            final List<SysCompanyDo> sysCompanyDos = sysCompanyMapper.queryPage(page);
            final List<CompanyResponse> responseList = CompanyConverter.INSTANCE.doToRes(sysCompanyDos);
            pageVO.setResult(responseList);
        }
        return Result.ok(pageVO);
    }
}
